package com.axend.aerosense.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.BuildConfig;
import com.axend.aerosense.R;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.BaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.WsApi;
import com.axend.aerosense.common.bean.ServerInfoBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.databinding.AppActivityMainBinding;

import java.lang.ref.WeakReference;

@Route(path = RouterActivityPath.App.PAGE_APP_MAIN)
public class SplashActivity extends MvvmBaseActivity<AppActivityMainBinding, BaseViewModel> {
    private final static int START = 0;
    private final static int END = 1;

    private static InternalHandler handler = null;
    static class InternalHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;

        /**
         * A constructor that gets a weak reference to the enclosing class. We
         * do this to avoid memory leaks during Java Garbage Collection.
         */
        public InternalHandler(Looper looper, Activity activity) {
            super(looper);
            weakRefActivity = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(msg.what == START){
                handler.sendEmptyMessageDelayed(END, 3 * 1000);

            }else if (msg.what == END){
                String tmp = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
                if(null != tmp && !TextUtils.isEmpty(tmp)){
                    ARouter.getInstance()
                            .build(RouterActivityPath.Main.PAGE_MAIN_MAIN)
                            .navigation();
                }else{
                    ARouter.getInstance()
                            .build(RouterActivityPath.Login.PAGE_LOGIN_HOME)
                            .withBoolean("jumpMainPage", true)
                            .navigation();
                }
                try{
                    Activity activity = weakRefActivity.get();
                    if (activity != null) {
                        activity.finish();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        init();
    }

    private void init(){
        setAppServer();

        handler = new InternalHandler(getMainLooper(), this);
        getLifecycle().addObserver(new LifecycleEventObserver(){

            @Override
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                if(event == Lifecycle.Event.ON_RESUME){
                    handler.sendEmptyMessage(START);
                }else if(event == Lifecycle.Event.ON_DESTROY){
                    if (null != handler){
                        handler.removeMessages(START);
                        handler.removeMessages(END);
                        handler = null;
                    }
                }
            }
        });
    }

    private void setAppServer(){
        if (!BuildConfig.DEBUG){
            return;
        }

        ServerInfoBean bean = MmkvHelper.getInstance()
                .getObject(Gobal.SAVE_KEY.DEBUG_SERVER_INFO_SAVE_KEY, ServerInfoBean.class);
        if (null == bean) { return; }

        String appServer = bean.getAppServer();
        String deviceServer = bean.getDeviceServer();
        String wsServer = bean.getWsServer();
        if (!TextUtils.isEmpty(appServer)) {
            UrlApi.setBaseUrl(appServer);
        }
        if (!TextUtils.isEmpty(deviceServer)) {
            UrlApi.setRadarTcpServerUrl(deviceServer);
        }
        if (!TextUtils.isEmpty(wsServer)) {
            WsApi.setBaseUrl(wsServer);
        }
    }

    @Override
    protected BaseViewModel getViewModel() {
        return  null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.app_activity_main;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}